package socket.nettydemo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

import java.io.DataOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by zhourui on 2016/9/2.
 */
public class NettyTcpServer {
    private static final int port = 12345;
    public static ConcurrentMap<String, ChannelHandlerContext> channelHandlerMap = new ConcurrentHashMap<>();
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            ch.pipeline().addLast(new TcpServerHandler());
                        }
                    }).option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

}

class TcpServerHandler extends ChannelInboundHandlerAdapter {
    private int handlerIndex;
    // 接收到新的数据
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException {
        try {
            ByteBuf in = (ByteBuf) msg;
            String clientInputStr = in.toString(CharsetUtil.UTF_8).trim();
            System.out.println("receive msg:"+clientInputStr);
            if (clientInputStr != null && !"".equals(clientInputStr)){
                String[] keyArray = clientInputStr.split(";");
                String key = keyArray[0];
                handlerIndex = Integer.parseInt(key);
                NettyTcpServer.channelHandlerMap.put(key,ctx);
                if (handlerIndex == 1) {
                    ChannelHandlerContext toSentChannel = NettyTcpServer.channelHandlerMap.get(keyArray[1]);
                    if (toSentChannel != null && !toSentChannel.isRemoved()){
                        System.out.println(toSentChannel.toString());
                        // 向客户端回复信息
                        String s = "message from client1. message is "+ clientInputStr;
                        byte[] responseByteArray = s.getBytes("UTF-8");
                        ByteBuf out = toSentChannel.alloc().buffer(responseByteArray.length);
                        out.writeBytes(responseByteArray);
                        toSentChannel.writeAndFlush(out);

                        String success = "success";
                        byte[] successResponseByteArray = success.getBytes("UTF-8");
                        ByteBuf successOut = ctx.alloc().buffer(successResponseByteArray.length);
                        successOut.writeBytes(successResponseByteArray);
                        ctx.writeAndFlush(successOut);
                    }else {
                        String success = "failed";
                        byte[] responseByteArray = success.getBytes("UTF-8");
                        ByteBuf successOut = ctx.alloc().buffer(responseByteArray.length);
                        successOut.writeBytes(responseByteArray);
                        ctx.writeAndFlush(successOut);
                    }
//                    // 发送到客户端
//                    byte[] responseByteArray = "你好".getBytes("UTF-8");
//                    ByteBuf out = ctx.alloc().buffer(responseByteArray.length);
//                    out.writeBytes(responseByteArray);
//                    ctx.writeAndFlush(out);
                }
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("channelActive");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx){
        System.out.println("channelInactive");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        NettyTcpServer.channelHandlerMap.remove(Integer.toString(handlerIndex));
        ctx.close();
    }
}